package com.epam.training.concurrency.second.task2;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Read data from buffer
 * 
 * @author Bogdan
 *
 */
class Reader implements Runnable {

	private Thread thread;
	private CircularBuffer buffer;

	private volatile boolean run = true;
	private static final int MAX_SLEEP = 1000;

	public void run() {
		Random random = new Random();

		while (run || !buffer.isEmpty()) {

			int number = buffer.read();
			System.out.format("Read number: %d%n", number);
			try {
				Thread.sleep(random.nextInt(MAX_SLEEP));
			} catch (InterruptedException e) {
				Logger.getLogger(Reader.class.getName()).log(Level.SEVERE,
						null, e);
			}
		}
	}

	Reader(CircularBuffer buffer) {
		this.buffer = buffer;
		thread = new Thread(this);
	}

	public void start() {
		thread.start();
	}
	
	public void stop() {
		run = false;
	}
}
